package yxm.zyf.love.CAS;

import sun.misc.Unsafe;

import java.lang.reflect.Field;
import java.util.HashMap;

/**
 * @author www
 */
public class CASTest {
    /**
     *
     * @author Zhangyf
     * @date 2020/9/4 16:52
     * @return sun.misc.Unsafe
     */
    public static Unsafe getInstance() throws NoSuchFieldException, IllegalAccessException {

        // 获取字段
        Field filed = Unsafe.class.getDeclaredField("theUnsafe");

        // 设置可访问
        filed.setAccessible(true);

        // 返回Unsafe实例
        return (Unsafe)filed.get(null);
    }


    /**需要CAS修改的字段*/
    private int i = 0;

    public int getI() {
        return i;
    }

    public void setI(int i) {
        this.i = i;
    }

    private HashMap map = null;

    public HashMap getMap() {
        return map;
    }

    public void setMap(HashMap map) {
        this.map = map;
    }

    public static void main(String[] args) throws NoSuchFieldException, IllegalAccessException {

        // 获取Unsafe实例
        Unsafe  unsafe = getInstance();

        // 获取字段 i 的偏移量
        CASTest test = new CASTest();
        Field field = test.getClass().getDeclaredField("i");
        long offset = unsafe.objectFieldOffset(field);

        // CAS修改，返回布尔值
        boolean isSuccess = unsafe.compareAndSwapInt(test,offset,0,1);

        HashMap mmp =new HashMap();
        mmp.put("aaa","bbb");
        boolean b = unsafe.compareAndSwapObject(test, offset, null, mmp);
        // 打印
        System.out.println(isSuccess);
        System.out.println(test.getI());
        System.out.println("b = " + b);
        System.out.println("test.getMap() = " + test.getMap());

    }
}

